import 'dart:convert';
import 'package:basic_common/app_theme.dart';
import 'package:basic_common/common_exports.dart';
import 'package:basic_common/local_storage.dart';
import 'package:basic_widgets/button_widget.dart';
import 'package:flutter/services.dart';
import '../model/cer_data_list.dart';
import '../model/cer_item_data.dart';
import '../model/cer_sign_data.dart';
import '../model/cer_sign_id_data.dart';

class LoginController extends GetxController {
  TextEditingController phoneNumberController = TextEditingController();
  TextEditingController accountController = TextEditingController();
  TextEditingController accounPwdController = TextEditingController();
  final isRead = false.obs;
  final btnIsEnable = false.obs;
  final isAccountLogin = false.obs; //登录方式切换
  //签名信息
  final signInfo = ''.obs;

  // 与Android通信 通道
  MethodChannel methodChannel = const MethodChannel("com.hnxyj.fwapp/plugin");
  final selGroupValue = ''.obs;

  /// 与原生Android数据传递
  static const basicMessageChannel = BasicMessageChannel(
      "com.hnxyj.fwapp/plugin/signLogin", StandardMessageCodec());

  @override
  void onInit() {
    super.onInit();
    _listenMessageFromNative();
  }

// 切换登录方式
  void switchType() {
    isAccountLogin.value = !isAccountLogin.value;
  }

  /// login 方法
  void postLogin() async {
    String phone = phoneNumberController.value.text;
    if (phone.isEmpty) {
      ToastUtils.toast("手机号不能为空");
      return;
    }
    if (!isRead.value) {
      ToastUtils.toast("请先阅读隐私协议");
      return;
    }
    HttpData? res =
        await ApiService().smsReq(data: {"phone": phone}, isShowLoading: true);
    if (res.msg == "success") {
      printInfo(info: "获取成功");

      RouterManager().navToSmsCode(ayguments: {"number": phone, "type": 1});
      // Get.toNamed("/smsCode", arguments: {"number": phone, "type": 1});
    }
  }

  /// 账号 密码登录
  void loginByAccount() async {
    String account = accountController.value.text;
    String password = accounPwdController.value.text;

    if (account.isEmpty || password.isEmpty) {
      ToastUtils.toast("账号或密码不能为空");
      return;
    }
    if (!isRead.value) {
      ToastUtils.toast("请先阅读隐私协议");
      return;
    }
    HttpData httpData = await ApiService().loginReq(data: {
      "scene": "医生端APP-账号登录",
      "loginMode": "password",
      "loginName": account,
      "password": password
    }, isShowLoading: true, loadingTitle: "正在登录...");
    if (httpData.msg == "success") {
      LoginData loginData = LoginData.fromJson(httpData.data);
      if (loginData.accessToken!.isNotEmpty) {
        LocalStorage.save("accessToken", loginData.accessToken!);
        LocalStorage.save("isLogin", true);
        ToastUtils.toast("登录成功");
        RouterManager().navToMainTab();
      } else {
        ToastUtils.toast("登录失败");
      }
    }
  }

  void setBtnEnable(bool val) {
    btnIsEnable.value = val;
  }

  // Dialog
  _alertSimpleDialog() async {
    Widget alertDialogs = await showDialog(
        context: Get.context!,
        builder: (context) {
          return SimpleDialog(
            // title: Text("提示"),
            children: <Widget>[
              Container(
                  padding: EdgeInsets.all(ScreenHelper.width(20)),
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(10)),
                  child: Text(
                    "您还未设置移动证书密码，请登录医生端后，在【我的】——【设置】模块进行移动证书密码设置后，方可使用签名登录",
                    style: TextStyle(fontSize: ScreenHelper.sp(14)),
                  )),
              Padding(
                padding:
                    EdgeInsets.symmetric(horizontal: ScreenHelper.width(10)),
                child: roundBtn(
                    text: "关闭",
                    onTap: () {
                      Get.back();
                    },
                    textColor: AppTheme.primyColor,
                    borderColor: AppTheme.primyColor,
                    bgColor: Colors.white),
              )
            ],
          );
        });
    return alertDialogs;
  }

  /// 弹出选择签名登录账号dialog
  Future<Widget> _showCerUserListDialog(List<CerItemData> userList) async {
    Widget alertDialogs = await showDialog(
        context: Get.context!,
        builder: (context) {
          return SimpleDialog(
            title: Container(
                alignment: Alignment.topCenter,
                margin: EdgeInsets.symmetric(vertical: ScreenHelper.height(10)),
                child: Text(
                  "请选择您要登录的用户",
                  style: TextStyle(
                      color: AppTheme.primyColor,
                      fontSize: ScreenHelper.sp(16)),
                )),
            children: <Widget>[
              Center(
                child: Obx(() => SizedBox(
                      height: ScreenHelper.height(120),
                      child: Column(
                        children: userList
                            .map<Widget>((e) => RadioListTile(
                                  title:
                                      Text(e.name!, textAlign: TextAlign.left),
                                  value: e.msmpid!,
                                  groupValue: selGroupValue.value,
                                  controlAffinity:
                                      ListTileControlAffinity.trailing,
                                  onChanged: (value) {
                                    selGroupValue.value = value!;
                                    update();
                                  },
                                ))
                            .toList(),
                      ),
                    )),
              ),
              Row(
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: ScreenHelper.width(10)),
                    child: roundBtn(
                        text: "关闭",
                        onTap: () {
                          Get.back();
                        },
                        textColor: AppTheme.weakTextColor,
                        borderColor: AppTheme.dartWeakTextColor,
                        bgColor: Colors.white),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: ScreenHelper.width(10)),
                    child: roundBtn(
                      text: "确定",
                      onTap: () {
                        selectCerUser(selGroupValue.value);
                      },
                      textColor: Colors.white,
                      borderColor: AppTheme.primyColor,
                      bgColor: AppTheme.primyColor,
                    ),
                  )
                ],
              )
            ],
          );
        });
    return alertDialogs;
  }

  /// 选择签名登录用户
  void selectCerUser(String mssId) async {
    String signId = await getCaAuth(mssId);
    if (signId.isNotEmpty) {
      signFromAndroid(signId, mssId);
    }
  }

// 获取原生签名方法
  signFromAndroid(String signId, String mssId) async {
    if (signId.isEmpty || mssId.isEmpty) {
      ToastUtils.toast("签名Id或唯一标识不能为空");
      return;
    }
    try {
      String signRes = await methodChannel
          .invokeMethod("getSignInfo", {"signId": signId, "mssId": mssId});
    } on PlatformException catch (error) {
      print("获取信息异常" + error.message!);
      return error.stacktrace!;
    }
  }

// 监听Android发送来的签名信息
  void _listenMessageFromNative() {
    //Flutter接收Native发来的消息
    basicMessageChannel.setMessageHandler((message) {
      signInfo.value = message!.toString();
      String res = message.toString();
      if (res.isEmpty) {
        ToastUtils.toast("签名信息不能为空");
        return Future.value("签名信息不能为空");
      }
      CerSignData cerSigndata =
          CerSignData.fromJson(jsonDecode(message.toString()));

      if (cerSigndata.type == "sign" && cerSigndata.status == "success") {
        String mssId = selGroupValue.value;

        caLogin(
            signValue: cerSigndata.signature!,
            csr: cerSigndata.cert!,
            mssId: mssId);
      } else {
        ToastUtils.toast(cerSigndata.msg!);
      }
      return Future.value(message.toString());
    });
  }

  /// 签名登录 获取账号列表
  getAccountList() async {
    //传递数据给android原生
    List<CerItemData> userList = [];
    try {
      String getCerList = await methodChannel.invokeMethod("getCerList", "");
      if (getCerList.isEmpty) {
        ToastUtils.toast("获取证书失败");
        return;
      }
      CerDataList cerDataList = CerDataList.fromJson(jsonDecode(getCerList));
      String userInfo = cerDataList.userInfos!;
      List list = json.decode(userInfo) as List;
      if (list.isNotEmpty) {
        list.forEach((element) {
          CerItemData itemData = CerItemData.fromJson(element);
          userList.add(itemData);
        });
        _showCerUserListDialog(userList);
      } else {
        _alertSimpleDialog();
      }
    } on PlatformException catch (error) {
      return error.stacktrace!;
    }
  }

  /// 签名登录 获取CA认证
  Future<String> getCaAuth(String mssid) async {
    if (mssid.isEmpty) {
      return ToastUtils.toast("MSSID不能为空");
    }
    String signId = '';
    HttpData res = await ApiService().getCaAuthInfo(data: {"msspid": mssid});
    if (res.code == 1) {
      CerSignIdData cerSigData = CerSignIdData.fromJson(res.data);
      if (cerSigData.message == "SUCCESS") {
        SignIdData signData = cerSigData.data!;
        if (signData != null) {
          signId = signData.signDataId!;
        }
      }
    }
    return signId;
  }

  /// CA登录
  void caLogin(
      {required String csr,
      required String mssId,
      required String signValue}) async {
    HttpData? httpData = await ApiService().loginReq(data: {
      "scene": "fwapp-dr",
      "scene_desc": "医生端app登录,签名登录",
      "loginMode": "ca",
      "msspid": mssId,
      "signValue": signValue,
      "cert": csr
    }, isShowLoading: true);
    if (httpData.msg == "success") {
      LoginData loginData = LoginData.fromJson(httpData.data);
      if (loginData.accessToken!.isNotEmpty) {
        LocalStorage.save("accessToken", loginData.accessToken!);
        LocalStorage.save("isLogin", true);
        // Get.offAndToNamed(AppRoutes.tabNav);
      } else {
        ToastUtils.toast("登录失败");
      }
    }
  }
}
